#!/usr/bin/python3

import requests
import os
import re
import zjl_util
import time
import hashlib
import random


class ximalaya(object):
 
    def __init__(self):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36"
        }
        self.sign = None
 
    def getServerTime(self):
        """
        获取喜马拉雅服务器的时间戳
        :return:
        """
        # 这个地址就是返回服务器时间戳的接口
        serverTimeUrl = "https://www.ximalaya.com/revision/time"
        response = requests.get(serverTimeUrl,headers = self.headers)
        return response.text
 
    def getSign(self,serverTime):
        """
        生成 xm-sign
        规则是 md5(ximalaya-服务器时间戳)(100以内随机数)服务器时间戳(100以内随机数)现在时间戳
        :param serverTime:
        :return:
        """
        nowTime = str(round(time.time()*1000))
 
        sign = str(hashlib.md5("himalaya-{}".format(serverTime).encode()).hexdigest()) + "({})".format(str(round(random.random()*100))) + serverTime + "({})".format(str(round(random.random()*100))) + nowTime
        # 将xm-sign添加到请求头中
        self.headers["xm-sign"] = sign
        self.sign = sign
        return sign

    def down_ximalaya(self, index_url, page_no, dir_path):

        host = index_url.replace("https://", "").replace("http://", "").split("/")[0]
        get_json_headers = {
            "Host": host,
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0",
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate, br",
            "xm-sign": "aec71c5e1158c343780ed6400b5453e2(27)1579179223520(4)1579179078903",
            "Connection": "keep-alive",
            "Referer": index_url,
            # "Cookie": "_xmLog=xm_k59fd3cfi4aql8; device_id=xm_1578737195570_k59fd4c2ohw6lr; Hm_lvt_4a7d8ec50cfd6af753c4f8aee3425070=1578737196,1579178334; 1&remember_me=y; 1&_token=59436631&D1FB179D840E48098B4A625DF6B7CF63NdV954A47712B887774644AB40B95EC8F11AD38191A88B4468A59D8E3A4C5EA1AD1; s&e=081d1b600afa395d53dcd767b3120408; x_xmly_traffic=utm_source%253A%2526utm_medium%253A%2526utm_campaign%253A%2526utm_content%253A%2526utm_term%253A%2526utm_from%253A; Hm_lpvt_4a7d8ec50cfd6af753c4f8aee3425070=1579178482; s&a=JS^%07_%05ASJ%0A%05%02YZN%07O%5C%0B%04%0AXAX%1C%5C^U^WK[V[CSBRCOK^XYBXM["
            }
        req.headers = get_json_headers
        s = webUrl.split("/")
        if s[len(s) - 1] == "":
            id_no = s[len(s) - 2]
        else:
            id_no = s[len(s) - 1]
        url = "https://www.ximalaya.com/revision/play/v1/show?num=" + str(page_no) + "&sort=0&size=30&ptype=0&id=" + id_no
        show_resp = requests.get(url, headers=get_json_headers)
        # print(show_resp.text)

        result_json = show_resp.json()

        items = result_json["data"]["tracksAudioPlay"]

        audio_url_pre = "https://www.ximalaya.com/revision/play/v1/audio?ptype=1&id="

        audio_url_head = {
            "Host": "aod.cos.tx.xmcdn.com",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate, br",
            "Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1"
        }

        for item in items:
            album_name = item["albumName"]
            track_name = item["trackName"]
            track_name = track_name.replace("（您的随手点赞！订阅！是对主播最大的支持）", "")
            track_id = item["trackId"]
            get_audio_url = audio_url_pre + str(track_id)
            print(get_audio_url)
            serverTime = self.getServerTime()
            sigin = self.getSign(serverTime)
            print('--------sign', sigin, '----------')
            show_resp = req.get(get_audio_url, headers=self.headers)
            print('------------------ show_resp')
            print(show_resp.text)
            print('------------------ show_resp end')
            audio_json = show_resp.json()
            down_url = audio_json["data"]["src"]

            file_dir = dir_path + "/" + album_name
            if os.path.exists(file_dir) is False:
                os.makedirs(file_dir)

            url_split = down_url.split(".")
            suffix = ".m4a"
            if len(url_split) > 1:
                suffix = "." + url_split[len(url_split) - 1]
            file_path = file_dir + "/" + track_name + suffix
            print(down_url)
            print(file_path)
            down_host = down_url.replace("https://", "").replace("http://", "").split("/")[0]
            audio_url_head['Host'] = down_host
            zjl_util.download(down_url, file_path, header=audio_url_head)
            # try:
            #     zjl_util.download(down_url, file_path, header=audio_url_head)
            #     # r = req.get(downUrl, headers=audioUrlHead)
            #     # with open(file_path, 'wb') as f:
            #     #     f.write(r.content)
            #     #     f.flush()
            # except:
            #     print("request error url:" + down_url)


# print(trackIdList)
#
# print("url:")
# for trackId in trackIdList:
#     getAudioUrl = audioUrlPre + str(trackId)
#     r = req.get(getAudioUrl)
#     audioJson = r.json()
#     print(audioJson["data"]["src"])


if __name__ == '__main__':

    req = requests.session()

    # 访问目录页
    webUrl = input("请输入喜马拉雅目录地址(首页)：")

    # webUrl = "https://www.ximalaya.com/keji/321245/"
    headers = {
        "Host": "www.ximalaya.com",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0",
        "Accept": "*/*",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br",
        "Connection": "keep-alive",
        }
    r = req.get(webUrl, headers=headers)
    result = r.text
    # print(result)
    fileResult = re.findall('<li class="page-item.*?"><a class="page-link _Mq" href="(.*?)"', result)
    index_uri_list = []
    for i in fileResult:
        index_uri_list.append(i)
    print('----------')
    print(index_uri_list)
    print('----------')

    default_dir = "/home/long655113/下载"
    base_dir = input("请输入小说下载目录(不包含资源名),直接回车选择默认目录(" + default_dir + "):")
    if len(base_dir) == 0:
        base_dir = default_dir

    ximalaya = ximalaya()
    serverTime = ximalaya.getServerTime()
    sigin = ximalaya.getSign(serverTime)
    print('--------sign', sigin, '----------')
    for i in range(0, len(index_uri_list)):
        ximalaya.down_ximalaya(webUrl, i + 1, base_dir)
    # ximalaya.down_ximalaya(webUrl, 5, base_dir)

